import {
  Component, DestroyRef,
  inject, OnInit,
  signal
} from '@angular/core';
import {
  PlacesContainer
} from '../places-container/places-container';
import {Place} from '../place.model';
import {Places} from '../places';
import { PlacesService } from '../places.service';

@Component({
  selector: 'app-available-places',
  imports: [
    PlacesContainer,Places
  ],
  templateUrl: './available-places.html',
  styleUrl: './available-places.css'

})
export class AvailablePlaces implements OnInit{
  places = signal<Place[] | undefined>(undefined);
  isFetching = signal(false);
  error = signal('');
  private placesService = inject(PlacesService);

  private destroyRef = inject(DestroyRef);


  ngOnInit(){
    this.isFetching .set(true);


    const subscription = this.placesService.loadAvailablePlaces()
      .subscribe({
      next:(places)=>{
        this.places.set(places);
      },
        error: (error) => {
          console.log(error);
          this.error.set(error.message);
        },
        complete:()=>{
          this.isFetching.set(false);
        }
    });

    this.destroyRef.onDestroy(()=>{
      subscription.unsubscribe();
    });
  }

  onSelectPlace(selectedPlace:Place){
      const subscription  = this.placesService.addPlaceToUserPlaces(selectedPlace)
        .subscribe({
        next:(resData) => console.log(resData),
      });

    this.destroyRef.onDestroy(()=>{
      subscription.unsubscribe();
    });
  }

}
